<template>
  <div class="fd-assign-pane">
    <!--TODO: 设置用户的习惯按钮 -->
    <el-tooltip class="item" content="自定义表格显示列" effect="dark" placement="top">
      <button class="set-fd-cell" @click="setDialogVisible = true"></button>
    </el-tooltip>
    <div class="custom-top">
      <div class="btn">
        <div class="left">
          <el-link icon="el-icon-magic-stick" @click="smartAssign">
            {{ $t('button.smartAssign') }}
          </el-link>

          <el-link icon="el-icon-folder-checked" style="margin-left: 15px" @click="fdSaveAll">
            {{ $t('button.submitAfterApprove') }}
          </el-link>
        </div>
        <div class="right">
          <el-radio-group v-model="dataType" size="mini">
            <el-radio-button label="all">{{ $t('button.all') }}</el-radio-button>
            <el-radio-button label="assigned">{{ $t('Project.assigned') }}</el-radio-button>
            <el-radio-button label="unAssigned">{{ $t('Project.unAssigned') }}</el-radio-button>
          </el-radio-group>
        </div>
      </div>
      <div class="total-result">
        <table>
          <tr>
            <td>总行数：{{ totalResult.totalLen }}</td>
            |
            <td>当前行数：{{ totalResult.currentLen }}</td>
          </tr>
        </table>
      </div>
    </div>
    <div class="custom-bottom">
      <VirtualTable
        :cb="totalCb"
        :filterable="true"
        :header-cell-style="$headerCellStyle"
        :rowStyle="rowStyle"
        rowKey="rfqRowId"
        :table="formDataFilter"
      >
        <!-- rowNo -->
        <Cell fix="left" :label="$t('FdData.rowNo')" :width="50">
          <template slot-scope="scope">
            <span>{{ scope.index + 1 }}</span>
          </template>
        </Cell>
        <!-- 正式物料编码 -->
        <Cell v-if="cellIsShow.IsPartNumber" fix="left" label="正式物料编码" prop="partNumber" />
        <!-- 物料描述 -->
        <Cell v-if="cellIsShow.IsPartName" fix="left" label="物料描述" prop="partName" />
        <!-- 材质描述 -->
        <Cell
          v-if="cellIsShow.IsMaterialDetail"
          fix="left"
          label="材质描述"
          prop="materialDetail"
        />
        <!-- ItemNo -->
        <Cell v-if="cellIsShow.IsItemNo" label="ItemNo" prop="itemNo" />
        <!-- 报价 -->
        <Cell v-if="cellIsShow.IsDpPrice" label="DP报价" prop="dpPrice" />
        <!-- 数量 -->
        <Cell v-if="cellIsShow.IsQty" label="数量" prop="qty" />
        <!-- 尺寸 -->
        <Cell v-if="cellIsShow.IsSize" label="尺寸" prop="size" />
        <!-- TempCode -->
        <Cell v-if="cellIsShow.IsSize" label="TempCode" prop="tempCode" />
        <!-- solution -->
        <Cell v-if="cellIsShow.IsSolution" label="Solution" prop="solution" />
        <!-- 工艺描述 -->
        <Cell v-if="cellIsShow.IsIdProcess" label="工艺描述" prop="idProcess" />
        <!-- 拥有者 -->
        <Cell v-if="cellIsShow.IsOwner" label="拥有者" prop="owner" />
        <!-- 供应商 -->
        <Cell v-if="cellIsShow.IsVendor1" label="一级供应商" prop="vendor1" />
        <Cell v-if="cellIsShow.IsVendor2" label="二级供应商" prop="vendor2" />
        <Cell v-if="cellIsShow.IsVendor3" label="三级供应商" prop="vendor3" />
        <Cell v-if="cellIsShow.IsVendor4" label="四级供应商" prop="vendor4" />
        <Cell v-if="cellIsShow.IsVendor5" label="五级供应商" prop="vendor5" />

        <!-- Category -->
        <Cell v-if="cellIsShow.IsCategory" label="Category" prop="category" />
        <!-- commodity -->
        <Cell v-if="cellIsShow.IsCommodity" label="Commodity" prop="commodity">
          <template slot-scope="scope">
            <BaseDblClick :scope="scope" @updateCell="updateCommodity">
              <template slot="one">
                {{ scope.row.commodity }}
              </template>
              <template slot="two">
                <el-select
                  v-model="scope.row.commodity"
                  v-focus
                  clearable
                  filterable
                  :placeholder="$t('select.placeholder')"
                >
                  <el-option
                    v-for="item in commodityList(scope.row.gcmFunction)"
                    :key="item.name"
                    :label="item.name"
                    :value="item.name"
                  >
                    <span style="float: left">{{ item.name }}</span>
                    <span style="float: right; color: #b4b4b4; font-size: 12px">
                      {{ item.gcmFunction }}
                    </span>
                  </el-option>
                </el-select>
              </template>
            </BaseDblClick>
          </template>
        </Cell>
        <!-- gcmOwner -->
        <Cell label="Gcm Owner" prop="gcmOwner">
          <template slot-scope="scope">
            {{ gcmOwnerById(scope.row.gcmOwner) }}
          </template>
        </Cell>
        <!-- RD Function -->
        <Cell v-if="cellIsShow.IsRdFunction" label="RD Function" prop="rdFunction" />
        <!-- gcmFunction -->
        <Cell v-if="cellIsShow.IsGcmFunction" label="Gcm Function" prop="gcmFunction">
          <template slot-scope="scope">
            <BaseDblClick :scope="scope" @updateCell="updateGcmFunction">
              <template slot="one">
                {{ scope.row.gcmFunction }}
              </template>
              <template slot="two">
                <el-select
                  v-model="scope.row.gcmFunction"
                  v-focus
                  clearable
                  filterable
                  :placeholder="$t('select.placeholder')"
                  style="width: 100%; height: 100%"
                  @change="changeGcmFunction(scope.row)"
                >
                  <el-option
                    v-for="item in $store.getters['enums/getGcmFunctionListOnly']"
                    :key="item"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </template>
            </BaseDblClick>
          </template>
        </Cell>
        <!-- 模穴数 -->
        <Cell v-if="cellIsShow.IsToolingCave" label="模穴数" prop="toolingCave" />
        <!-- 重量 -->
        <Cell v-if="cellIsShow.IsWeight" label="重量" prop="weight" />
        <!-- Cost -->
        <Cell v-if="cellIsShow.IsCost" label="Cost" prop="cost" />
        <!-- trackingOption -->
        <Cell v-if="cellIsShow.IsTrackingOption" label="Tracking & Option" prop="trackingOption" />
      </VirtualTable>
    </div>

    <!--图片对话框-->
    <BaseDialog
      v-if="picDialogVisible"
      :title="$t('FdData.viewPic')"
      :visible.sync="picDialogVisible"
      width="500px"
    >
      <BaseIdpPicView
        :idp-token="idpToken"
        :pic-list="picList"
        @cancel="picDialogVisible = false"
      />
    </BaseDialog>
    <!--TODO: 设置显示列对话框 -->
    <BaseDialog
      v-if="setDialogVisible"
      title="设置显示列"
      :visible.sync="setDialogVisible"
      width="50%"
    >
      <RfqCellShowSet
        :cellIsShow="cellIsShow"
        :pageId="pageId"
        @cancel="setDialogVisible = false"
        @saveOperationData="saveOperationData"
      />
    </BaseDialog>
  </div>
</template>
<script>
import { RfqAssignSaveList, RfqAssignCommit } from '@/api/rfq/rfq'
// import { idpGetToken } from '@/api/quote/idp'
import { rdgcmList } from '@/api/quote/rdgcm'
import { categoryCommodityMp } from '@/api/quote/category'
// import { fdRowPictureList } from '@/api/quote/fd-row-picture'
import { RfqAssignSaveSingle } from '@/api/rfq/rfq'
import Cell from '@/widgets/VirtualTable/Cell'
import VirtualTable from '@/widgets/VirtualTable/Table'
import RfqCellShowSet from '../../components/RfqCellShowSet'
import rfqCell from '@/mixins/rfqCell'

export default {
  name: 'RfqAssignPane',

  components: { VirtualTable, Cell, RfqCellShowSet },
  mixins: [rfqCell],

  props: {
    inputData: {
      default: () => null,
      type: Object
    },
    shareDataList: {
      default: () => [],
      type: Array
    }
  },
  data() {
    return {
      // 当前修改行
      currentEditRow: {},
      // 当前序号
      currentEditIndex: 0,
      // 当前行号
      currentRowNo: 0,
      // gcm function 映射表
      gcmFunctionMp: [],
      // category-commodity映射表
      categoryCommodityMpList: [],
      // 是否智能进行匹配
      startSmartAssign: false,
      // idp token
      idpToken: '',
      // 每一行的图片数据
      picList: [],
      // 图片对话框可见标识
      picDialogVisible: false,
      // 显示是否分配数据
      dataType: 'unAssigned',
      // 合计信息
      totalResult: {
        totalLen: 0,
        currentLen: 0
      },
      setDialogVisible: false,
      pageId: 'RfqAssignPane',
      cellIsShow: {},

      // 触发提交之后未完成分配列表
      unDoneAssignList: []
    }
  },
  computed: {
    formDataFilter() {
      if (this.dataType === 'all') {
        return this.shareDataList
      } else if (this.dataType === 'assigned') {
        return this.shareDataList.filter(item => item.isGcmCommit)
      } else {
        return this.shareDataList.filter(item => !item.isGcmCommit)
      }
    }
  },
  created() {},
  mounted() {
    this.pageDataInit()
    this.getRdgcmList()
    this.getCategoryCommodityMpList()
    // 页面加载时 智能分配
    // this.smartAssign()
  },
  methods: {
    rowStyle(index, row) {
      if (this.unDoneAssignList.find(item => item.rfqRowId === row.rfqRowId)) {
        return {
          backgroundColor: '#ffdada'
        }
      }
    },
    pageDataInit() {
      this.$store.dispatch('commodity/initCommodityCollectsLazy')
    },
    // 获取gcm function 映射表
    async getRdgcmList() {
      const res = await rdgcmList({})
      this.gcmFunctionMp = res.data // rdfunction+category ==> GcmFunction
    },
    // 获取commodity映射表
    async getCategoryCommodityMpList() {
      const res = await categoryCommodityMp({})
      this.categoryCommodityMpList = res.data
    },
    // isGcmCost 为true不分配
    async smartAssign() {
      try {
        await this.$confirmBox(this.$t('button.smartAssign'), 'success')
        this.shareDataList.forEach(item => {
          const isGcmCost = item.isGcmCost
          if (isGcmCost) return
          const result = this.gcmFunctionMp.find(
            mp => mp.rdFunction === item.rdFunction && mp.category === item.category
          )
          if (result) {
            item.gcmFunction = result.gcmFunction
          }
        })
        this.$nextTick(() => {
          this.commoditySmartMapping()
        })
      } catch (error) {
        console.log(error)
      }
    },
    // commodity智能映射
    async commoditySmartMapping() {
      try {
        this.shareDataList.forEach(row => {
          const isGcmCost = row.isGcmCost
          if (isGcmCost) return
          this.categoryCommodityMpList.forEach(mp => {
            if (
              (row.gcmFunction &&
                mp.gcmFunction &&
                row.gcmFunction.toLowerCase() !== mp.gcmFunction.toLowerCase()) ||
              (!row.category && !row.newMaterialGroup && !row.newMaterialDetail)
            ) {
              return
            }
            if (row.newMaterialDetail) {
              this.haveMaterialDetail(row, mp)
            } else {
              this.noValMaterialDetail(row, mp)
            }
          })
        })
        // 保存所有数据
        this.afterSmartAssign()
      } catch (error) {
        console.log(error)
      }
    },
    // MaterialDetail有值
    haveMaterialDetail(row, mp) {
      if (
        (!row.category && !row.newMaterialGroup) ||
        (row.category &&
          mp.category &&
          row.category.toLowerCase() === mp.category.toLowerCase() &&
          !row.newMaterialGroup) ||
        (!row.category &&
          row.newMaterialGroup &&
          mp.materialGroup &&
          row.newMaterialGroup.toLowerCase() === mp.materialGroup.toLowerCase()) ||
        (row.category &&
          mp.category &&
          row.category.toLowerCase() === mp.category.toLowerCase() &&
          row.newMaterialGroup &&
          mp.materialGroup &&
          row.newMaterialGroup.toLowerCase() === mp.materialGroup.toLowerCase())
      ) {
        this.isIncludeMaterialDetail(row, mp)
      }
    },
    // MaterialDetail没有值的情况
    noValMaterialDetail(row, mp) {
      if (
        (row.category && mp.category && row.category.toLowerCase() === mp.category.toLowerCase()) ||
        (row.newMaterialGroup &&
          mp.materialGroup &&
          row.newMaterialGroup.toLowerCase() === mp.materialGroup.toLowerCase())
      ) {
        row.commodity = mp.commodity
      }
    },
    // 判断行内materialDetail是否包含查询表的materialDetail
    isIncludeMaterialDetail(row, mp) {
      console.log('1')
      const materialDetailArr = String(mp.materialDetail)
        .toLowerCase()
        .split('|')
      const result = materialDetailArr.filter(item => {
        return (
          String(row.newMaterialDetail)
            .toLowerCase()
            .indexOf(item) === -1
        )
      })
      if (result.length === 0) {
        row.commodity = mp.commodity
      }
    },

    // 智能匹配之后的数据提交
    async afterSmartAssign() {
      try {
        const fdRowAssignList = this.shareDataList
          .filter(item => item.gcmFunction) // && item.gcmOwner
          .map(item => {
            return {
              commodity: item.commodity,
              rfqRowId: item.rfqRowId,
              gcmFunction: item.gcmFunction,
              partNumber: item.partNumber,
              tempCode: item.tempCode
            }
          })

        if (fdRowAssignList.length > 0) {
          await RfqAssignSaveList(fdRowAssignList)
          this.$emit('update')
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 保存全部匹配结果
    async fdSaveAll() {
      try {
        await this.$confirmBox(this.$t('button.submit'), 'success')
        this.unDoneAssignList = this.shareDataList.filter(item => {
          if (item.isGcmCost) return false
          const isAssignEnd = item.gcmFunction && item.commodity
          // 将未完成分配的放进数组中
          return !isAssignEnd
        })
        if (this.unDoneAssignList.length > 0) {
          return this.$message({
            message: '分配未完成',
            type: 'error',
            duration: 1500
          })
        }
        await RfqAssignCommit(
          { rfqId: this.inputData.rfqId, version: this.inputData.version },
          { msgSuccess: true, msgError: true }
        )
        this.$emit('cancel')
      } catch (error) {
        console.log(error)
      }
    },

    // 查看fd每一行图片列表
    // async fdPicList(data, isNew) {
    //   const res = await fdRowPictureList({ rfqRowId: data.rfqRowId, isNew: isNew })
    //   this.picList = res.data
    //   this.picDialogVisible = true
    // },
    async updateGcmFunction(data) {
      try {
        const gcmFunction = data.row.gcmFunction
        // const gcmOwner = gcmFunction ? this.inputData[gcmFunction.toLowerCase() + 'Owner'] : ''
        await RfqAssignSaveSingle({
          commodity: data.row.commodity,
          rfqRowId: data.row.rfqRowId,
          gcmFunction: gcmFunction,
          partNumber: data.row.partNumber,
          tempCode: data.row.tempCode
          // gcmOwner: gcmOwner
        })
        this.$emit('update')
      } catch (error) {
        console.log(error)
      }
    },
    async updateCommodity(data) {
      try {
        await RfqAssignSaveSingle({
          commodity: data.row.commodity,
          rfqRowId: data.row.rfqRowId,
          gcmFunction: data.row.gcmFunction,
          partNumber: data.row.partNumber,
          tempCode: data.row.tempCode
          // gcmOwner: data.row.gcmOwner
        })
        this.$emit('update')
      } catch (error) {
        console.log(error)
      }
    },
    // gcmFunction 变化 对应的 commodity置空
    changeGcmFunction(data) {
      // data.commodity = ''
      const arr = this.categoryCommodityMpList.filter(mp => mp.gcmFunction === data.gcmFunction)
      const index = arr.findIndex(item => item.commodity === data.commodity)
      index === -1 && (data.commodity = '')
    },
    totalCb(args) {
      this.totalResult = { ...args }
    },
    commodityList(gcmFunction) {
      if (gcmFunction) {
        return this.$store.getters['commodity/getCommodityCollectsByGcmFunction'](gcmFunction)
      } else {
        return this.$store.getters['commodity/getCommodityCollects']
      }
    },

    afterUpdate(data) {
      const rfqRowId = data.row.rfqRowId

      const index = this.shareDataList.findIndex(item => item.rfqRowId === rfqRowId)

      index !== -1 && (this.shareDataList[index] = data.row)

      this.$emit('update')
    }
  }
}
</script>
<style lang="scss" scoped>
.fd-assign-pane {
  .custom-top {
    width: calc(100% - 17px);
    height: 80px;
    display: flex;
    flex-direction: column;
    justify-content: flex-end;

    .btn {
      margin-top: 15px;
      width: 100%;
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
  }
  .custom-bottom {
    position: absolute;
    top: 80px;
    bottom: 0;
    left: 20px;
    right: 25px;
    .el-select {
      width: 100%;
    }
    /deep/.el-input__icon {
      line-height: unset !important;
    }
    /deep/input {
      height: 24px !important;
      border: none;
    }
  }
}
</style>
